package com.mapper.test.mapper.handler;

import com.mapper.test.entity.Address;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-06-04 下午12:58
 */
public class AddressTypeHandler extends BaseTypeHandler<Address> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Address parameter, JdbcType jdbcType) throws SQLException {
        //1.对数据进行验证
        if (parameter == null) {
            return;
        }

        //2.从Address对象中取出具体的对象
        String province = parameter.getProvince();
        String city = parameter.getCity();
        String street = parameter.getStreet();

        //3.拼装成一个字符串
        // 规则:各个值之间用,分开
        StringBuilder builder = new StringBuilder();
        builder.append(province)
                .append(",")
                .append(city)
                .append(",")
                .append(street);

        String parameterValue = builder.toString();

        //4.设置参数
        ps.setString(i, parameterValue);
    }

    @Override
    public Address getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 1. 根据字段名从rs对象中获取字段值
        String columnValue = rs.getString(columnName);

        // 2.验证columnValue是否有效
        if (columnValue == null || columnValue.length() == 0 || !columnValue.contains(",")) {
            return null;
        }

        return getAddressFromString(columnValue);
    }

    @Override
    public Address getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        // 1. 根据字段名从rs对象中获取字段值
        String columnValue = rs.getString(columnIndex);

        // 2.验证columnValue是否有效
        if (columnValue == null || columnValue.length() == 0 || !columnValue.contains(",")) {
            return null;
        }

        return getAddressFromString(columnValue);
    }

    @Override
    public Address getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        // 1. 根据字段名从rs对象中获取字段值
        String columnValue = cs.getString(columnIndex);

        // 2.验证columnValue是否有效
        if (columnValue == null || columnValue.length() == 0 || !columnValue.contains(",")) {
            return null;
        }

        return getAddressFromString(columnValue);
    }

    /**
     * 根据,对字符串进行拆分,并创建Address返回
     */
    private Address getAddressFromString(String str) {
        String[] parts = str.split(",");
        return new Address(parts[0], parts[1], parts[2]);
    }
}
